from django.shortcuts import render
from django.views import View
import random
from django_redis import get_redis_connection
from django import http
import logging

from apps.verifications.libs.captcha.captcha import captcha
# from apps.verifications.libs.yuntongxun.ccp_sms import CCP
from celery_tasks.sms.tasks import ccp_send_sms_code

# Create your views here.
# 创建日志器
logger = logging.getLogger('django')


class SMSCodeView(View):
    """短信验证码视图类
    GET http://www.meiduo.site:8000/sms_codes/mobile/
    """
    def get(self, request, mobile):
        # 创建redis连接对象
        redis_conn = get_redis_connection('verify_code')
        # 接收参数
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({'code': 400, 'errmsg': '频繁发送短信'})

        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        # 校验参数,mobile不用校验，因为在路由转换器提取时就已经校验，不匹配时，直接返回404
        if not all([image_code_client, uuid]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        # # 创建redis连接对象
        # redis_conn = get_redis_connection('verify_code')

        # 提取图形验证码(存在服务器内存)
        image_code_server = redis_conn.get('img_%s' % uuid)

        if image_code_server is None:
            return http.JsonResponse({'code': 400, 'errmsg': '图形验证码已失效'})

        # 删除图形验证码(数据库)，以防恶意测试图形验证码
        try:
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)

        # 对比图形验证码
        # 从redis数据库提取的类型是字节bytes类型字符串
        image_code_server = image_code_server.decode()
        if image_code_client.lower() != image_code_server.lower():
            return http.JsonResponse({'code': 400, 'errmsg': '输入的图形验证码有误'})

        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)
        # 创建管道
        pl = redis_conn.pipeline()
        # 保存短信验证码
        # redis_conn.setex('sms_%s' % mobile, 300, sms_code)
        pl.setex('sms_code_%s' % mobile, 300, sms_code)

        # 为以发送短信验证码的手机进行标记60秒过期时间与前端计时一样
        # redis_conn.setex('send_flag_%s' % mobile, 60, 1)
        pl.setex('send_flag_%s' % mobile, 60, 1)

        # 执行管道
        pl.execute()

        # 发送短信验证码
        # 修改前
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)

        # delay(mobile, sms_code)实现异步，解耦，响应结果不受发送短信验证码影响
        # 代码执行到这里后，该函数不立即执行，先放行，让下一个代码先执行
        ccp_send_sms_code.delay(mobile, sms_code)

        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': '发送短信成功'})


class ImageCodeView(View):
    """图形验证码视图类
    GET http://www.meiduo.site:8000/image_codes/uuid/
    """
    def get(self, request, uuid):
        # 调用工具captcha生成图形验证码
        text, image = captcha.generate_captcha()

        # 连接redis，创建连接对象
        redis_conn = get_redis_connection('verify_code')

        # 使用连接对象保存数据到redis
        redis_conn.setex('img_%s' % uuid, 300, text)

        return http.HttpResponse(image, content_type='image/jpg')
